/**
 * WebSocket事件中心 - 优化版本
 * 直接更新Vuex状态，减少事件分发开销
 */

import store from '@/store';
import { Message } from 'element-ui';

class WebSocketEventCenter {
  constructor() {
    this.isInitialized = false;
    this.messageQueue = [];
    this.batchTimer = null;
    this.batchSize = 10;
    this.batchDelay = 50; // 50ms批量处理
  }

  /**
   * 初始化事件中心
   */
  init() {
    if (this.isInitialized) return;
    
    // 监听WebSocket原始事件
    this.setupWebSocketListeners();
    this.isInitialized = true;
    
    console.log('WebSocket事件中心已初始化');
  }

  /**
   * 设置WebSocket监听器
   */
  setupWebSocketListeners() {
    // 监听WebSocket连接状态
    window.addEventListener('websocket:connected', this.handleConnection);
    window.addEventListener('websocket:disconnected', this.handleDisconnection);
    
    // 监听消息事件
    window.addEventListener('websocket:message', this.handleMessage);
  }

  /**
   * 处理WebSocket连接
   */
  handleConnection = (event) => {
    console.log('WebSocket连接成功');
    store.commit('chat/SET_CONNECTION_STATUS', true);
    
    // 触发连接初始化
    this.dispatchToStore('connectInit', event.detail);
  };

  /**
   * 处理WebSocket断开
   */
  handleDisconnection = (event) => {
    console.log('WebSocket连接断开');
    store.commit('chat/SET_CONNECTION_STATUS', false);
  };

  /**
   * 处理WebSocket消息
   */
  handleMessage = (event) => {
    const { cmd, data } = event.detail;
    
    // 根据命令类型直接更新Vuex状态
    switch (cmd) {
      case 30001: // 单聊消息
        this.handleSingleChatMessage(data);
        break;
      case 30005: // 群聊消息
        this.handleGroupChatMessage(data);
        break;
      case 30004: // 撤回消息
        this.handleRetractMessage(data);
        break;
      case 30010: // 已读同步
        this.handleReadSync(data);
        break;
      case 30009: // 解散群聊
        this.handleDisbandGroup(data);
        break;
      default:
        console.log('未处理的消息类型:', cmd);
    }
  };

  /**
   * 处理单聊消息
   */
  handleSingleChatMessage(data) {
    // 直接更新Vuex状态，无需事件分发
    store.commit('chat/ADD_MESSAGE', {
      chatId: data.receiveId || data.senderId,
      message: this.normalizeMessage(data)
    });

    // 更新未读计数
    this.updateUnreadCount(data.receiveId || data.senderId, 1);

    // 自动滚动到底部（通过Vuex状态变化触发）
    this.triggerAutoScroll();
  }

  /**
   * 处理群聊消息
   */
  handleGroupChatMessage(data) {
    store.commit('chat/ADD_MESSAGE', {
      chatId: data.groupChatId,
      message: this.normalizeMessage(data)
    });

    this.updateUnreadCount(data.groupChatId, 1);
    this.triggerAutoScroll();
  }

  /**
   * 处理撤回消息
   */
  handleRetractMessage(data) {
    store.commit('chat/RETRACT_MESSAGE', {
      messageId: data.messageId,
      chatId: data.chatId
    });
  }

  /**
   * 处理已读同步
   */
  handleReadSync(data) {
    store.commit('chat/MARK_MESSAGES_READ', {
      chatId: data.chatId,
      messageIds: data.messageIds
    });
  }

  /**
   * 处理解散群聊
   */
  handleDisbandGroup(data) {
    store.commit('chat/CLEAR_CHAT_HISTORY', data.groupChatId);
    store.commit('chatList/REMOVE_CHAT', data.groupChatId);
  }

  /**
   * 标准化消息格式
   */
  normalizeMessage(data) {
    return {
      id: data.id || data.messageId,
      content: data.content,
      messageType: data.messageType || 0,
      createTime: data.createTime || new Date().toISOString(),
      senderId: data.senderId,
      receiveId: data.receiveId,
      groupChatId: data.groupChatId,
      isMyselfMsg: data.isMyselfMsg || false,
      // 其他必要字段...
      ...data
    };
  }

  /**
   * 更新未读计数
   */
  updateUnreadCount(chatId, increment = 1) {
    store.commit('chat/UPDATE_UNREAD_COUNT', { chatId, increment });
  }

  /**
   * 触发自动滚动
   */
  triggerAutoScroll() {
    // 通过Vuex状态变化触发滚动，而不是直接操作DOM
    store.commit('chat/SET_SHOULD_SCROLL', true);
  }

  /**
   * 分发到Vuex Store
   */
  dispatchToStore(action, payload) {
    store.dispatch(`chat/${action}`, payload);
  }

  /**
   * 批量处理消息（防抖）
   */
  batchProcessMessages() {
    if (this.messageQueue.length === 0) return;

    const messages = this.messageQueue.splice(0, this.batchSize);
    
    // 批量更新Vuex状态
    store.commit('chat/BATCH_ADD_MESSAGES', messages);
    
    // 如果还有消息，继续处理
    if (this.messageQueue.length > 0) {
      this.batchTimer = setTimeout(this.batchProcessMessages, this.batchDelay);
    }
  }

  /**
   * 添加消息到队列
   */
  addToQueue(message) {
    this.messageQueue.push(message);
    
    if (!this.batchTimer) {
      this.batchTimer = setTimeout(this.batchProcessMessages, this.batchDelay);
    }
  }

  /**
   * 销毁事件中心
   */
  destroy() {
    if (this.batchTimer) {
      clearTimeout(this.batchTimer);
    }
    
    window.removeEventListener('websocket:connected', this.handleConnection);
    window.removeEventListener('websocket:disconnected', this.handleDisconnection);
    window.removeEventListener('websocket:message', this.handleMessage);
    
    this.isInitialized = false;
  }
}

// 创建单例实例
export const webSocketEventCenter = new WebSocketEventCenter();

// 自动初始化
webSocketEventCenter.init();

export default webSocketEventCenter;
